import {Component, Input, OnInit} from '@angular/core';
import {FetchService} from "../../../../core/net/fetch.service";
import {NzFormatEmitEvent, NzMessageService} from "ng-zorro-antd";
import * as moment from "moment";
import * as _ from "lodash";

@Component({
    selector: 'app-agri-irr-multi',
    templateUrl: './agri-irr-multi.component.html',
    styleUrls: ['./agri-irr-multi.component.scss', '../agriculture.component.scss']
})
export class AgriIrrMultiComponent implements OnInit {
    treeValue = '23';
    listData = [];
    defaultKeys = [];
    trIds = [];

    baseOpt: any = {
        tooltip: {
            trigger: "axis",
            axisPointer: {
                label: {
                    backgroundColor: "#505765"
                }
            }
        },
        legend: {
            data: [],
            bottom: 10
        },
        xAxis: {
            type: "category",
            data: []
        },
        yAxis: [
            {
                name: "单位：万亩",
                type: "value"
            }
        ],
        series: [
            {
                name: "",
                type: "bar",
                data: []
            }
        ]
    };
    irrOptChange: any = {};
    waterOptChange: any = {};
    irrType = '1';  //  1-夏秋灌 2-冬灌
    tableData = [];
    tableHead = [];

    @Input()
    get dateModal() {
        // this.queryInfo();
        return this._dateModal;
    }

    set dateModal(val) {
        if (moment(val[0]).year() !== moment(val[1]).year()) {
            this.message.error('请勿跨年选择');
        } else {
            if (val[0] && val[1]) {
                if ((moment(val[0]).month() < 3 && moment(val[1]).month() >= 3) || (moment(val[0]).month() < 9 && moment(val[1]).month() >= 9)) {
                    this.message.error('请勿跨灌季选择');
                } else {
                    this._dateModal = val;
                    if (this.trIds.length) {
                        this.queryInfo();
                    }
                }
            }
        }
    }

    // tslint:disable-next-line:variable-name
    _dateModal = [new Date(), new Date()];

    constructor(private fetchService: FetchService,
                private message: NzMessageService) {
    }

    ngOnInit() {
        this.getListData();
    }

    getListData() {
        this.fetchService.post<any>('sys/sysApiInfo/queryApiData', {
            apicode: this.treeValue
        }).subscribe(res => {
            console.log(res);
            res.forEach(item => {
                item.title = item.name;
                item.key = item.id;
                item.isLeaf = true;
            });
            this.listData = res;
            this.defaultKeys = [this.listData[0].key];
            this.trIds = this.defaultKeys;
            this.queryInfo();
        });
    }

    selectedAreaChanged(event: NzFormatEmitEvent): void {
        console.log(event);
        this.trIds = event.checkedKeys.map(item => {
            return item.key;
        });
        this.queryInfo();
    }

    queryInfo(): void {
        const params = {
            stDate: moment(this.dateModal[0]).format('YYYY-MM-DD'),
            edDate: moment(this.dateModal[1]).format('YYYY-MM-DD'),
            dId: this.trIds.join(',')
        };
        if (this.treeValue === '23') {
            _.assign(params, {
                queryType: '1'
            });
        } else if (this.treeValue === '22') {
            _.assign(params, {
                queryType: '2'
            });
        }

        this.fetchService.post('report/irr/mutipleCompareByCountry', params).subscribe(res => {
            if (res) {
                this.irrType = res['flag'];
                // const legendArr = _.reduce(res['irr'].map(i => i.list), (result, prev) => {
                //     return result.concat(prev);
                // }, []);

                let legendArr = [];
                res['irr'].forEach(item => {
                    const nameArr = item.list.map(o => {
                        return o.corp;
                    });
                    legendArr = _.uniq([...legendArr, ...nameArr]);
                });
                this.tableHead = res['irr'].map(o => {
                    return o.name;
                });

                this.irrOptChange = {
                    legend: {
                        data: legendArr
                    },
                    xAxis: {
                        data: this.tableHead
                    },
                    series: legendArr.map(o => {
                        return {
                            name: o,
                            type: "bar",
                            data: res['irr'].map(obj => {
                                const cropObj = _.find(obj.list, i => {
                                    return i.corp === o;
                                });
                                return cropObj ? cropObj.val : '';
                            })
                        };
                    })
                };
                this.waterOptChange = {
                    legend: {
                        data: ['用水量']
                    },
                    xAxis: {
                        data: res['use'].map(o => {
                            return o.area;
                        })
                    },
                    yAxis: [
                        {
                            name: "单位：亿m³"
                        }
                    ],
                    series: [{
                        name: '用水量',
                        type: "bar",
                        data: res['use'].map(obj => {
                            return obj.val;
                        })
                    }]
                };


                const inletData = legendArr.map(cropName => {
                    return {
                        name: cropName,
                    };
                });
                const useData = {
                    name: '用水量'
                };
                this.tableHead.forEach(key => {
                    inletData.forEach(item => {
                        const nameObj = _.find(res['irr'], obj => {
                            return obj.name === key;
                        });
                        const cropObj = _.find(nameObj.list, o => {
                            return o.corp === item.name;
                        });
                        item[key] = cropObj ? cropObj.val : '';

                    });

                    useData[key] = _.find(res['use'], obj => {
                        return obj.area === key;
                    }).val;
                });

                this.tableData = [...inletData, useData];

            }
        });
    }
}
